/**
 * Created by Administrator on 2016/8/26.
 */


var router = require("express").Router();
var rPacketDao = require('./rPacketModel');
var taskDao = require('../task/taskModel');
var moment = require('moment');
var schedule=require('node-schedule');
var rule = new schedule.RecurrenceRule();


var RPList = [];

getAllSysRPList();

/*
* 如果rule还未赋值(重启项目，或插入第一个红包时)rule.hour==null,rule.minute==null,rule.second==0,则重置所有next_time=currentTime+时间间隔+随机（分）
* 找到最小的next_time,然后将最小的next_time赋值给rule,将数据写入数据库中
* 随机分Math.random()*10随机秒Math.random()*60,Math.ceil()向下取整
*
* 在正常运转时，将第一个next_time与rule对比，
* 如果，next_time<rule,表示这是一个新加的红包，重置当前next_time = currentTime+时间间隔+随机（分+秒），直至找到next_time==rule，然后发此红包，并将next_time = next_time+时间间隔，找到最小next_time
* 如果，next_time==rule，则发此红包，并将next_time = next_time+时间间隔，写入数据库，否则rule=next_time,break退出循环
* 如果，next_time>rule(一般不会出现此情况)，rule = next_time
*
*
* */

function getAllSysRPList() {
    rPacketDao.getAllSysRPList(function (err, data) {
        if (err) {
            return err;
        }

        RPList = data;
        if (data.length == 0) {
            return RPList;
        } else {
            for (i = 0; i < RPList.length; i++) {
                RPList[i].next_time = moment(RPList[i].next_time).format('YYYY-MM-DD HH:mm:ss')
            }
        }
        if (rule.hour == null && rule.minute == null && rule.second == 0) {
            //项目重启，所有有效红包的next_time
            console.log("重启了机器");

            var currentTime = moment().format('YYYY-MM-DD HH:mm:00');   //当前时间


            //倒计时时间（分钟），
            var countDown = 0;

            for (i = 0; i < RPList.length; i++) {
                //var randomMinute = Math.ceil(Math.random()*5)+RPList[i].time_interval;
                var randomMinute = RPList[i].time_interval;
                RPList[i].next_time = moment(currentTime).add(randomMinute, 'minutes').format('YYYY-MM-DD HH:mm:ss');

                if(i == 0){
                    countDown = randomMinute;
                }else if(randomMinute<countDown){
                    countDown = randomMinute;
                }
            }

            //处理秒

            console.log('倒计时（分）=='+(countDown-1));
            console.log('倒计时（秒）=='+(60-new Date(moment().format('YYYY-MM-DD HH:mm:ss')).getSeconds()));


            var times = [];
            for(var i=0; i<60; i++){
                times.push(i);
            }
            rule.minute = times;

            RPList.forEach(function (item) {
                rPacketDao.updateNextTime(item.sys_red_packet_id, item.next_time, function (err, data) {
                    if (err) {
                        return err;
                    }

                })
            })


        } else {
            var currentTime = moment().format("YYYY-MM-DD HH:mm:00");
            //倒计时时间（分钟），
            var countDown = RPList[0].time_interval;

            var flag = 0;

            RPList.forEach(function(item){
                if(item.next_time == currentTime){
                    rPacketDao.addRPacket(item.total_money,item.total_quantity,item.red_packet_type,item.task_id,'',function(err,data){
                        if(err){
                            return err;
                        }
                        item.next_time = moment(item.next_time).add(item.time_interval,"minutes").format("YYYY-MM-DD HH:mm:00");
                        rPacketDao.updateNextTime(item.sys_red_packet_id, item.next_time,function(err,data){
                            if(err){
                                return err;
                            }
                            console.log('系统发红包啦');
                            flag++;
                            if(item.time_interval<countDown){
                                countDown = item.time_interval;
                            }
                            //当发出红包后才会让前端更新倒计时时间
                            if(flag == RPList.length){
                                console.log('打印倒计时===>');
                                console.log(countDown);
                            }

                        })
                    })
                }else{

                    item.next_time = new Date(item.next_time);
                    var nowTime = new Date(currentTime);
                    var time_interval = Math.round((item.next_time.getTime()-nowTime.getTime())/1000/60);

                    if(time_interval<countDown){
                        countDown = time_interval;
                    }
                    flag++;
                    if(flag == RPList.length){
                        console.log('打印倒计时===>');
                        console.log(countDown);
                    }
                }
            })


        }



    })
}

var setRule = function(minNextTime,rule){
    minNextTime = new Date(minNextTime);

    rule.year = minNextTime.getFullYear();
    rule.month = minNextTime.getMonth() + 1;
    //rule.date = 0-30,表示日历中的1-31日
    rule.date = minNextTime.getDate() - 1;
    rule.hour = minNextTime.getHours();
    rule.minute = minNextTime.getMinutes();
    rule.second = minNextTime.getSeconds();
}


schedule.scheduleJob(rule,function(){
    console.log('执行JOB');

    getAllSysRPList();
})


//获取系统红包列表
function getSysRPList(req,res){
    var page = 1;
    var size = 5;
    if(req.body != null){
        page = req.body.page;
        size = req.body.size;
    }
    var object = {
        results:[],
        counts:0
    }
    rPacketDao.getSysRPList(page,size,function(err,results){
        if(err){
            return res.json(500,err);
        }
        object.results = results;
        rPacketDao.getSysRPCount(function(err,counts){
            if(err){
                return res.json(500,err);
            }
            object.counts = counts;
            return res.json(200,object);
        })

    })

}

//创建红包
function createSysRPacket(req,res){
    if(!req.body){
        return res.json(500,'添加失败!!!')
    }else{
        var form = req.body;
        var rPacketType = form.rPacketType;
        var totalMoney = form.totalMoney;
        var totalQuantity = form.totalQuantity;
        var timeInterval = form.timeInterval;
        var taskId = form.taskId;
    }
    rPacketDao.addSysRPacket(rPacketType,totalMoney,totalQuantity,timeInterval,taskId,function(err,data){
        if(err){
            return res.json(500,err);
        }
        return res.json(200,data);
    })

}

//修改系统红包状态
function changeSysRPStatus(req,res){
    if(!req.query){
        return res.json(500,'添加失败!!!')
    }else{
        var form = req.query;
        var sysRPacketId = form.sysRPacketId;
        var status = form.status;
    }
    rPacketDao.updateSysRPStatus(sysRPacketId,status,function(err,data){
        if(err){
            return res.json(500,err);
        }
        return res.json(200,data);
    })

}

function changeSysRPState(req,res){
    if(!req.query){
        return res.json(500,'添加失败!!!')
    }else{
        var form = req.query;
        var sysRPacketId = form.sysRPacketId;

    }
    rPacketDao.changeSysRPState(sysRPacketId,function(err,data){
        if(err){
            return res.json(500,err);
        }
        return res.json(200,data);
    })
}

function getSysRPDetail(req,res){
    if(!req.query){
        return res.json(500,'添加失败!!!')
    }else{
        var form = req.query;
        var sysRPacketId = form.sysRPacketId;

    }
    rPacketDao.getSysRPDetail(sysRPacketId,function(err,data){
        if(err){
            return res.json(500,err);
        }
        return res.json(200,data[0]);
    })
}

function updateRPacket(req,res){
    console.log(req.body);
    if(!req.body){
        return res.json(500,'添加失败!!!')
    }else{
        var form = req.body;
        var sysRPacketId = form.sys_red_packet_id;
        var totalMoney = form.total_money;
        var totalQuantity = form.total_quantity;
        var timeInterval = form.time_interval;

    }
    rPacketDao.updateRPacket(sysRPacketId,totalMoney,totalQuantity,timeInterval,function(err,data){
        if(err){
            return res.json(500,err);
        }
        return res.json(200,data);
    })
}

//获取红包任务列表task_type=2,state=1,status=2
function getRPTask(req,res){

    taskDao.getRPTaskList(function(err,data){
        if(err){
            return res.json(500,err);
        }
        return res.json(200,data);
    })
}

router.post("/getSysRPList", getSysRPList);
router.post("/createSysRPacket", createSysRPacket);
router.get("/changeSysRPStatus", changeSysRPStatus);
router.get("/changeSysRPState", changeSysRPState);
router.get("/getSysRPDetail", getSysRPDetail);
router.post("/updateRPacket", updateRPacket);
router.post("/getRPTask", getRPTask);



module.exports = router;
